﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models.ViewModel.News;
using ELearning.Common;
using ELearning.Common.Helpers;
using ELearning.Common.Http;
using ELearning.Models;
using ELearning.Models.ViewModel.Message;
using NLog;

namespace ELearning.API.Controllers.AdminControllers
{
    /// <summary>
    /// 新增相关功能
    /// </summary>
    public class MessageController : BaseApiController
    {
        /// <summary>
        /// 消息操作service
        /// </summary>
        private EMessageService MessageService => new EMessageService();

        /// <summary>
        /// 消息与角色操作service
        /// </summary>
        private RMessageRoleService rmrService => new RMessageRoleService();

        /// <summary>
        /// 角色用户关联操作service
        /// </summary>
        private RRoleUserService RRoleUserService => new RRoleUserService();

        /// <summary>
        /// 用户操作service
        /// </summary>
        private ESysUserService ESysUserService => new ESysUserService();

        /// <summary>
        /// 消息发送记录
        /// </summary>
        private EMessageLogService EMessageLogService => new EMessageLogService();

        /// <summary>
        /// 获取消息列表
        /// </summary>
        [HttpPost, Route("api/emessage/GetList")]
        public ServiceResponse<MessageViewModel> GetList(MessageRequest request)
        {
            var viewModel = new MessageViewModel();
            Expression<Func<EMessage, bool>> whereLamdba = (u) => u.IsDelete == false;
            if (!string.IsNullOrEmpty(request.Title))
                whereLamdba = whereLamdba.And(u => u.Title.Contains(request.Title));
            if (!string.IsNullOrEmpty(request.SubTitle))
                whereLamdba = whereLamdba.And(u => u.SubTitle.Contains(request.SubTitle));
            if (request.State > 0)
                whereLamdba = whereLamdba.And(u => u.State.Equals(request.State));
            var messages = MessageService.FindPageList(request.Page, request.PageSize, out var totalRecord, "CreateTime", "DESC", whereLamdba);
            if (messages != null)
            {
                viewModel.TotalCount = totalRecord;
                var msgIds = messages.Select(m => m.Id).ToList();
                var rmrs = rmrService.FindList(r => msgIds.Contains(r.MessageId) && !r.IsDelete).ToList();

                foreach (var item in messages)
                {
                    var n = new MessageItem
                    {
                        Id = item.Id,
                        CreateTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                        Creater = item.Creater,
                        IsStick = item.IsStick.ToString("yyyy-MM-dd HH:mm"),//item.IsStick.Equals(new DateTime(1900, 1, 2, 0, 0, 0)) ? "否" : "是",
                        ModifyTime = item.ModifyTime.ToString("yyyy-MM-dd HH:mm"),
                        Modify = item.Modifyer,
                        ReadCount = item.ReadCount,
                        Title = item.Title,
                        Text = item.Text,
                        Sort = item.Sort,
                        SubTitle = item.SubTitle,
                        Type = item.Type,
                        State = item.State,
                        RoleIdList = rmrs.Where(r => r.MessageId == item.Id).Select(m => m.RoleId).ToList()
                    };
                    viewModel.NewsItems.Add(n);
                }
            }

            return ServiceResponse<MessageViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 添加消息
        /// </summary>
        [HttpPost, Route("api/emessage/AddModel")]
        public object AddModel(MessageItem viewModel)
        {
            var message = new EMessage
            {
                Id = GuidUtil.NewSequentialId(),
                CreateTime = DateTime.Now,
                Creater = CurrentUserModel?.LoginName ?? string.Empty,
                IsDelete = false,
                IsStick = DateTime.Now,
                ModifyTime = DateTime.Now,
                Modifyer = CurrentUserModel?.LoginName ?? string.Empty,
                ReadCount = 0,
                SendTime = DateTime.Now,
                Sort = viewModel.Sort,
                State = 1,
                Type = 2,
                Title = viewModel.Title,
                SubTitle = viewModel.SubTitle,
                Text = viewModel.Text
            };

            var regStr = "^[^\\n\\\\]+$";
            var checkReg = Regex.IsMatch(viewModel.Text, regStr);
            if (!checkReg)
                return ServiceResponse<bool>.SuccessResponse(CommonConst.MessageTextNotVaild, false);

            if (viewModel.RoleIdList != null)
            {
                var rmrs = new List<RMessageRole>();
                foreach (var roleId in viewModel.RoleIdList)
                {
                    var rmr = new RMessageRole
                    {
                        Id = GuidUtil.NewSequentialId(),
                        Creater = CurrentUserModel?.LoginName ?? string.Empty,
                        CreateTime = DateTime.Now,
                        IsDelete = false,
                        MessageId = message.Id,
                        RoleId = roleId
                    };
                    rmrs.Add(rmr);
                }
                rmrService.AddsNoSaveChange(rmrs);
            }
            MessageService.Add(message);
            return ServiceResponse<MessageItem>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 发送消息
        ///	status：true/false（成功/失败）
        ///	msg：提示消息
        ///	errorMsg: 异常提醒（http status 不为200时返回）
        ///	data: 返回数据结构体
        ///	http status：200代表请求成功
        ///                ：401/400 异常
        /// </summary>
        /// <param name="dealerCode">经销商代码:(AgentNumber)</param>
        /// <param name="msgContent">消息体</param>
        /// <param name="employeeNo">员工编号(Unumber)</param>
        [HttpGet,Route("api/emessage/SendMsg")]
        public MessageSendRespViewModel SendMsg(string dealerCode, string msgContent, string employeeNo)
        {
            return MessageService.SendMsg(dealerCode, msgContent, employeeNo);
        }

        /// <summary>
        /// 销售助手发送消息
        /// </summary>
        /// <param name="jxsh">经销商号码</param>
        /// <param name="content">消息内容</param>
        /// <param name="czydm">操作员代码</param>
        /// <param name="czymc">操作员名称</param>
        /// <param name="title">消息标题</param>
        /// <param name="messageId">消息id</param>
        /// <returns></returns>
        [HttpGet, Route("api/emessage/SendXszsMsg")]
        public XszsMessageSendRespViewModel SendXszsMsg(string jxsh, string content, string czydm, string czymc, string title, string messageId)
        {
            return MessageService.SendXszsMsg(jxsh, content, czydm, czymc, title, messageId);
        }

        /// <summary>
        /// 更新消息
        /// </summary>
        [HttpPost, Route("api/emessage/UpdateModel")]
        public ServiceResponse<bool> UpdateModel(MessageItem viewModel)
        {
            var regStr = "^[^\\n\\\\]+$";
            var checkReg = Regex.IsMatch(viewModel.Text, regStr);
            if (!checkReg)
                return ServiceResponse<bool>.SuccessResponse(CommonConst.MessageTextNotVaild, false);

            var message = MessageService.Find(m => m.Id == viewModel.Id && !m.IsDelete);
            message.ModifyTime = DateTime.Now;
            message.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
            message.Title = viewModel.Title;
            message.SubTitle = viewModel.SubTitle;
            message.Text = viewModel.Text;
            message.Title = viewModel.Title;

            if (message.Type == 1)
                return ServiceResponse<bool>.SuccessResponse(CommonConst.SysMessageTextNotOprate, false);

            var deleteRmrs = rmrService.FindList(r => r.MessageId == message.Id).ToList();
            rmrService.DeletesNoSaveChange(deleteRmrs);

            if (viewModel.RoleIdList != null)
            {
                var rmrs = new List<RMessageRole>();
                foreach (var roleId in viewModel.RoleIdList)
                {
                    var rmr = new RMessageRole
                    {
                        Id = GuidUtil.NewSequentialId(),
                        Creater = CurrentUserModel?.LoginName ?? string.Empty,
                        CreateTime = DateTime.Now,
                        IsDelete = false,
                        MessageId = message.Id,
                        RoleId = roleId
                    };
                    rmrs.Add(rmr);
                }
                rmrService.AddsNoSaveChange(rmrs);
            }

            MessageService.Update(message);
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="id">消息id</param>
        [HttpGet, Route("api/emessage/DeleteModel")]
        public ServiceResponse<bool> DeleteModel(Guid id)
        {
            var message = MessageService.Find(m => m.Id == id && !m.IsDelete);
            if (message != null)
            {
                if (message.Type == 1)
                    return ServiceResponse<bool>.SuccessResponse(CommonConst.SysMessageTextNotOprate, false);

                message.IsDelete = true;
                MessageService.Update(message);
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        [HttpPost, Route("api/emessage/PublishModel")]
        public object PublishModel(Guid id, int status)
        {
            try
            {
                var message = MessageService.Find(m => m.Id == id);
                if (message != null)
                {
                    message.State = 3;
                    var users = ESysUserService.GetSendUserByMsgId(id);

                    var minutes = 2;
                    var str = $"请等待{minutes}分钟";
                    if (users.Count > 100)
                    {
                        minutes = (users.Count + 99) / 100;
                        str = $"请等待{minutes}分钟";
                        if (minutes > 59)
                        {
                            var hours = minutes / 60;
                            minutes = minutes - hours * 60;
                            if (minutes > 0)
                                str = $"请等待{hours}小时{minutes}分钟";
                            else
                                str = $"请等待{hours}小时";
                        }
                    }

                    message.SendTime = DateTime.Now;
                    MessageService.Update(message);
                    return ServiceResponse<string>.SuccessResponse(CommonConst.OprateSuccessStr, str);
                }

            }
            catch (Exception ex)
            {
                var logEvent = LogHelper.CreateErrorLogEventInfoWithArgumentPattern(ex, nameof(id), id, nameof(status), status);
                logEvent.Message = string.Format("调用骏客接口的时候培训接口出错：{0}", logEvent.Message);
                LogManager.GetCurrentClassLogger().Log(logEvent);
                return ServiceResponse<string>.WarningResponse(logEvent.Message);
            }
            return ServiceResponse<string>.SuccessResponse(CommonConst.OprateSuccessStr);
        }

        /// <summary>
        /// 置顶和取消置顶
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost, Route("api/emessage/TopModel")]
        public object TopModel(Guid id, int status)
        {
            var b = false;
            //var news = NewsService.GetNews(id);
            //if (news != null)
            //{
            //    if (status == 1)
            //    {
            //        news.IsStick = DateTime.Now;
            //    }
            //    else
            //    {
            //        news.IsStick = news.CreateTime;
            //    }
            //        news.ReleaseTime = DateTime.Now;
            //    b=NewsService.Update(news);
            //}
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, b);
        }

        /// <summary>
        /// 获取消息发送记录
        /// </summary>
        [HttpPost, Route("api/emessage/GetMessageLog")]
        public ServiceResponse<MessageLogViewModel> GetMessageLog(MessageLogRequest request)
        {
            Expression<Func<EMessageLog, bool>> whereLamdba = (u) => u.IsDelete == false && u.MessageId == request.MessageId;
            if (request.Status > -1)
            {
                var status = request.Status == 1;
                whereLamdba = whereLamdba.And(l => l.Status == status);
            }
            var logs = EMessageLogService.FindPageList(request.Page, request.PageSize, out var totalRecord, "", "", whereLamdba);
            var userIds = logs.Select(l => l.UserId).ToList();
            var users = ESysUserService.FindList(u => userIds.Contains(u.UserID)).ToList();
            var viewModel = new MessageLogViewModel { TotalCount = totalRecord };
            var message = MessageService.Find(m => m.Id == request.MessageId && !m.IsDelete);
            foreach (var log in logs)
            {
                var user = users.Find(u => u.UserID == log.UserId);
                var t = new MessageLogItem
                {
                    UserId = log.UserId,
                    MessageId = request.MessageId,
                    Note = log.Note,
                    Status = log.Status,
                    UserName = user?.UserName ?? string.Empty,
                    Unumber = user?.Unumber ?? string.Empty,
                    MessageContent = message?.Text ?? string.Empty,
                    MessageTitle = message?.Title ?? string.Empty
                };
                viewModel.Items.Add(t);
            }

            return ServiceResponse<MessageLogViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }
    }
}